<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        .box, .bigImg{
            position: relative;
            float: left;
            margin-top: 50px;
            margin-left: 100px;
            width: 450px;
            height: 450px;
            border: 1px solid #ccc;
        }
        .box img{
            width: 100%;
        }
        .bigImg img{
            position: absolute;
            top: 0;
            left: 0;
            width: 200%;
        }
        .bigImg{
            display: none;
            overflow: hidden;
        }
        .mask{
            position: absolute;
            top: 0;
            left: 0;
            width: 50%;
            height: 50%;
            background-color: rgba(0, 0, 0, .3);
        }
    </style>
</head>
<body>
    <div class="box">
        <img src="img1.jpg" alt="">
        <div class="mask" hidden></div>
    </div>
    <div class="bigImg">
        <img src="img1.jpg" alt="">
    </div>

    <script>
        var box = document.querySelector('.box');
        var mask = document.querySelector('.mask');
        var bigImg = document.querySelector('.bigImg img');
        var big = document.querySelector('.bigImg');

        box.onmousemove = function () {
            mask.hidden = false;
            big.style.display = 'block';

            var pageY = event.pageY;
            var pageX = event.pageX;

            var minX = 0;
            var minY = 0;
            var maxX = box.clientWidth - mask.offsetWidth;
            var maxY = box.clientHeight - mask.offsetHeight;

            var left = pageX - box.offsetLeft - mask.offsetWidth/2;
            var top = pageY - box.offsetTop - mask.offsetHeight/2;
            
            if (pageX - box.offsetLeft - mask.offsetWidth/2 < minX) {
                left = minX;
            }
            if (pageX - mask.offsetWidth/2 - box.offsetLeft > maxX) {
                left = maxX;
            }
            if (pageY - box.offsetTop - mask.offsetHeight/2 < minY) {
                top = minY;
            }
            if (pageY - mask.offsetHeight/2 - box.offsetTop > maxY) {
                top = maxY;
            }

            mask.style.left = left + 'px';
            mask.style.top = top + 'px';
            bigImg.style.top = -top*2 + 'px';
            bigImg.style.left = -left*2 + 'px';

        }
        box.onmouseleave = function () {
            mask.hidden = true;
            big.style.display = 'none';
        }
    </script>
</body>
</html>